import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.concurrent.Future;

import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;

class UrlFetchServiceWrapper {
	Future<HTTPResponse> futureResponse;
	byte[] contents = null;

	public UrlFetchServiceWrapper(String url) {
		URLFetchService service = URLFetchServiceFactory.getURLFetchService();

		try {
			futureResponse = service.fetchAsync(new URL(url));
		} catch(MalformedURLException mue) { mue.printStackTrace(); }
	}

	private void recvContents() {
		if (contents != null)
			return;
		try {
			contents = futureResponse.get().getContent();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public InputStream getInputStream() {
		recvContents();

		return new ByteArrayInputStream(contents, 0, contents.length);
	}

	public byte[] getBytes() {
		recvContents();

		return contents;
	}
};
